package com.aiyige.page.publish.selecttraingcard;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.eventbus.EventSelectTraingCard;
import com.aiyige.model.Page;
import com.aiyige.model.moment.backup.CardBackup;
import com.aiyige.model.moment.entity.Moment;
import com.aiyige.page.publish.selecttraingcard.adapter.TraingCardAdapter;
import com.aiyige.page.publish.selecttraingcard.model.TraingCard;
import com.aiyige.utils.AccountUtil;
import com.aiyige.utils.ListUtil;
import com.aiyige.utils.dialog.LoadingDialog;
import com.aiyige.utils.widget.CommonDataView;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Call;

@Route(path = ARouterConfig.SelectTraingCardPage)
public class SelectTraingCardPage extends AppCompatActivity implements CommonDataView.RetrofitStub {
    public static final String EXTRA_KEY_SELECT_TRAING_CARD_DATA = "com.aiyige.extra.EXTRA_KEY_SELECT_TRAING_CARD_DATA";
    @BindView(R.id.titleBackBtn)
    ImageView titleBackBtn;
    @BindView(R.id.titleTv)
    TextView titleTv;
    @BindView(R.id.titleActionBtn)
    Button titleActionBtn;
    @BindView(R.id.cdv)
    CommonDataView cdv;
    TraingCardAdapter traingCardAdapter;
    @Autowired
    TraingCard[] selectedCards = null;
    @Autowired
    boolean postEvent = false;
    List<TraingCard> preSelectedTraingCardList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_select_traing_card);
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
        preSelectedTraingCardList = new LinkedList<>();
        if (selectedCards != null) {
            for (TraingCard item : selectedCards) {
                preSelectedTraingCardList.add(item);
            }
        }

        titleTv.setText(R.string.support_traing_card_multi_select);
        titleActionBtn.setText(R.string.ok);
        traingCardAdapter = new TraingCardAdapter();
        traingCardAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                TraingCard traingCard = traingCardAdapter.getItem(position);
                traingCard.setSelected(!traingCard.isSelected());
                if (!traingCard.isSelected()) {
                    removePreSelect(traingCard.getId());
                }
                traingCardAdapter.setData(position, traingCard);
            }
        });
        cdv.config(traingCardAdapter, this);
        cdv.doRefreshRequest();
    }

    public ArrayList<TraingCard> getSelectedItem() {
        ArrayList<TraingCard> traingCardList = new ArrayList<>();
        for (TraingCard traingCard : traingCardAdapter.getData()) {
            if (traingCard.isSelected()) {
                traingCardList.add(traingCard);
            }
        }
        return traingCardList;
    }

    @Override
    public void onBackPressed() {
        if (postEvent) {
            EventBus.getDefault().post(EventSelectTraingCard.newBuilder()
                    .resultCode(EventSelectTraingCard.RESULT_CANCEL)
                    .build());
        }
        super.onBackPressed();
    }

    @OnClick({R.id.titleBackBtn, R.id.titleActionBtn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.titleBackBtn: {
                finish();
                if (postEvent) {
                    EventBus.getDefault().post(EventSelectTraingCard.newBuilder()
                            .resultCode(EventSelectTraingCard.RESULT_CANCEL)
                            .build());
                }
                break;
            }
            case R.id.titleActionBtn: {
                ArrayList<TraingCard> traingCardList = getSelectedItem();
                if (!traingCardList.isEmpty()) {
                    Intent data = new Intent();
                    data.putParcelableArrayListExtra(EXTRA_KEY_SELECT_TRAING_CARD_DATA, traingCardList);
                    setResult(RESULT_OK, data);
                    finish();
                    if (postEvent) {
                        EventBus.getDefault().post(EventSelectTraingCard.newBuilder()
                                .resultCode(EventSelectTraingCard.RESULT_OK)
                                .traingCardList(traingCardList)
                                .build());
                    }
                }
                break;
            }
        }
    }

    public void restoreSelect(List<TraingCard> traingCardList) {
        if (!ListUtil.isEmpty(preSelectedTraingCardList)) {
            outerLoop:
            for (TraingCard selectedCard : preSelectedTraingCardList) {
                for (TraingCard card : traingCardList) {
                    if (selectedCard.getId().equals(card.getId())) {
                        card.setSelected(true);
                        continue outerLoop;
                    }
                }
            }
        }
    }

    public void removePreSelect(String id) {
        if (!ListUtil.isEmpty(preSelectedTraingCardList)) {
            Iterator<TraingCard> iterator = preSelectedTraingCardList.iterator();
            while (iterator.hasNext()) {
                TraingCard traingCard = iterator.next();
                if (traingCard.getId().equals(id)) {
                    iterator.remove();
                    break;
                }
            }
        }
    }

    @Override
    public Call<ResponseBody> call(long currentPage) {
        return ApiManager.getService().availableTraingCard(currentPage, 15);
    }

    @Override
    public CommonDataView.HandleResult handleResponse(String respJson, List resultList) {
        try {
            Page page = JSON.parseObject(respJson, Page.class);
            List<CardBackup> cardBackupList = new LinkedList<>();
            if (!TextUtils.isEmpty(page.getContent())) {
                cardBackupList.addAll(JSON.parseArray(page.getContent(), CardBackup.class));
            }
            List<TraingCard> respTraingCardList = new LinkedList<>();
            for (CardBackup cardBackup : cardBackupList) {
                int cardType;
                switch (cardBackup.getCardType()) {
                    case Moment.TRAINING_CARD_TYPE_TIME_CARD:
                        cardType = TraingCard.TYPE_TIME_CARD;
                        break;
                    case Moment.TRAINING_CARD_TYPE_RECHARGEABLE_CARD:
                        cardType = TraingCard.TYPE_PREPAID_CARD;
                        break;
                    case Moment.TRAINING_CARD_TYPE_MEASURED_CARD:
                        cardType = TraingCard.TYPE_COUNT_CARD;
                        break;
                    default:
                        cardType = TraingCard.TYPE_COUNT_CARD;
                        break;
                }
                respTraingCardList.add(TraingCard.newBuilder()
                        .id(cardBackup.getId())
                        .selected(false)
                        .title(cardBackup.getTitle())
                        .type(cardType)
                        .build());
            }
            restoreSelect(respTraingCardList);
            resultList.addAll(respTraingCardList);
            return new CommonDataView.HandleResult(page.isLast());
        } catch (Exception e) {
            return new CommonDataView.HandleResult(e.getMessage());
        }
    }
}
